<script setup lang="ts">
  import { ref, computed, watch, reactive } from 'vue';
  import { useBooleanStore } from '@/store';
  import {
    querySortInfoSearch,
    querySendToolSearch,
  } from '@/api/inventory-management';
  import {
    QuerySortInfoParam,
    QuerySendToolParam,
  } from '@/api/inventory-management/types';
  import { Notification } from '@arco-design/web-vue';

  import * as XLSX from 'xlsx';
  import { saveAs } from 'file-saver';

  const booleanStore = useBooleanStore();
  const emit = defineEmits(['infoArray', 'toolArray']);
  const pageSize = ref<number>(10);
  const pageNumber = ref<number>(1);
  const planeNoInput = ref<boolean>();
  const checkValue = ref<string>('checkInfo');
  const tableData = ref<any>();
  const formValues = reactive({
    planeNo: '',
    aoCode: '',
    itemCode: '',
    qualityCode: '',
    station: '',
    isSort: '',
    status: '',
    state: '',
    isDailyPlan: '',
  });
  const infoTableColumns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      fixed: 'left',
      width: 50,
    },
    {
      title: 'AO号',
      dataIndex: 'aoCode',
      fixed: 'left',
      width: 180,
    },
    {
      title: '分拣状态',
      dataIndex: 'isSort',
      fixed: 'left',
      width: 80,
    },
    {
      title: '配套状态',
      dataIndex: 'state',
      fixed: 'left',
      width: 80,
    },
    {
      title: '配送状态',
      dataIndex: 'status',
      fixed: 'left',
      width: 80,
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      fixed: 'left',
      width: 200,
    },
    {
      title: '图号名称',
      dataIndex: 'itemName',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '型号',
      dataIndex: 'mProductNumber',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '拆分后合格证号',
      dataIndex: 'newMesCheckQualiticationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '拆分前合格证号',
      dataIndex: 'mesCheckQualiticationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '是否带证',
      dataIndex: 'wmsIsPaper',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '配送交接单是否带证',
      dataIndex: 'wmsIsPaper',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '装配图号',
      dataIndex: 'repartAss',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '需求数量',
      dataIndex: 'itemQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '配套数量',
      dataIndex: 'matchQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '分拣数量',
      dataIndex: 'packageCount',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '退库数量',
      dataIndex: 'retrunQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '二次配套数量',
      dataIndex: 'secondMatchQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '机型',
      dataIndex: 'productCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '批次',
      dataIndex: 'batchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '站位',
      dataIndex: 'station',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '托盘编码',
      dataIndex: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '小车编码',
      dataIndex: 'carCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '日计划时间',
      dataIndex: 'dailyTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '配送时间',
      dataIndex: 'sendDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '类型',
      dataIndex: 'addType',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '接收备注',
      dataIndex: 'receiveRemark',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: 'wmsItemInventoryId',
      dataIndex: 'wmsItemInventoryId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: 'msAoMatchInfoId',
      dataIndex: 'msAoMatchInfoId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: 'msTaskAoId',
      dataIndex: 'msTaskAoId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '配送交接单ID',
      dataIndex: 'wmsDeliveryPlanId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const toolTableColumns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      key: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '托盘',
      dataIndex: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '小车',
      dataIndex: 'carCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '站位',
      dataIndex: 'station',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  // 配套明细搜索数据
  const infoData = computed<QuerySortInfoParam>(() => ({
    queryMap: {
      planeNo: formValues.planeNo,
      aoCode: formValues.aoCode,
      itemCode: formValues.itemCode,
      qualityCode: formValues.qualityCode,
      station: formValues.station,
      isSort: formValues.isSort,
      status: formValues.status,
      state: formValues.state,
      isDailyPlan: formValues.isDailyPlan,
    },
    page: {
      total: 0,
      pageSize: pageSize.value,
      currentPage: pageNumber.value,
    },
  }));
  // 配套托盘搜索数据
  const toolData = computed<QuerySendToolParam>(() => ({
    queryMap: {
      planeNo: formValues.planeNo,
      aoCode: formValues.aoCode,
      itemCode: formValues.itemCode,
      qualityCode: formValues.qualityCode,
      station: formValues.station,
      isSort: formValues.isSort,
      status: formValues.status,
      state: formValues.state,
      isDailyPlan: formValues.isDailyPlan,
    },
    page: {
      total: 0,
      pageSize: pageSize.value,
      currentPage: pageNumber.value,
    },
  }));
  async function handleSearch() {
    if (!formValues.planeNo) {
      planeNoInput.value = true;
      Notification.warning({
        title: '提示',
        content: '架次不能为空',
        closable: true,
      });
      return;
    }
    if (checkValue.value === 'checkInfo') {
      const newData = await querySortInfoSearch(infoData.value);
      if (newData) {
        emit('infoArray', newData);
        tableData.value = newData.list;
      } else {
        Notification.error({
          title: '失败',
          content: newData.message ? newData.message : '查询失败',
          closable: true,
        });
      }
    } else {
      const newData = await querySendToolSearch(toolData.value);
      if (newData) {
        emit('toolArray', newData);
        tableData.value = newData.list;
      } else {
        Notification.error({
          title: '失败',
          content: newData.message ? newData.message : '查询失败',
          closable: true,
        });
      }
    }
  }
  function reset() {
    Object.keys(formValues).forEach((key) => {
      (formValues as Record<string, any>)[key] = '';
    });
    planeNoInput.value = false;
    emit('infoArray', null);
    emit('toolArray', null);
    tableData.value = null;
  }
  // 导出参数
  function exportParam(excelData: any, excelColumns: any) {
    const emptyRows = Array(1).fill({});
    const dataWithEmptyRows = emptyRows.concat(excelData);
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(dataWithEmptyRows, {
      header: excelColumns.map((h: any) => h.dataIndex),
      skipHeader: true,
    });
    XLSX.utils.sheet_add_aoa(
      ws,
      [excelColumns.map((itemName: any) => itemName.title)],
      {
        origin: 'A1', // 表头开始的位置
      }
    );
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    saveAs(
      new Blob([wbout], { type: 'application/octet-stream' }),
      'export.xlsx'
    );
  }
  function exportExcel() {
    if (!tableData.value) {
      Notification.warning({
        title: '警告',
        content: '当前页面无需要导出数据',
        closable: true,
      });
      return;
    }
    if (checkValue.value === 'checkInfo') {
      // 根据列数据保留表数据，过滤多余的表格数据
      const filteredData = tableData.value.map((item: any) => {
        const newItem: any = {};
        infoTableColumns.forEach((columnIndex: any) => {
          if (columnIndex.dataIndex in item) {
            newItem[columnIndex.dataIndex] = item[columnIndex.dataIndex];
          }
        });
        return newItem;
      });
      exportParam(filteredData, infoTableColumns);
    }
    if (checkValue.value === 'checkTool') {
      // 根据列数据保留表数据，过滤多余的表格数据
      const filteredData = tableData.value.map((item: any) => {
        const newItem: any = {};
        toolTableColumns.forEach((columnIndex: any) => {
          if (columnIndex.dataIndex in item) {
            newItem[columnIndex.dataIndex] = item[columnIndex.dataIndex];
          }
        });
        return newItem;
      });
      exportParam(filteredData, toolTableColumns);
    }
  }
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 36 || booleanStore.num5 === 37) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });
</script>

<template>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6" class="input-col">
      <a-input
        v-model="formValues.planeNo"
        placeholder="架次"
        size="large"
        :error="planeNoInput"
        @press-enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" class="input-col">
      <a-input
        v-model="formValues.aoCode"
        placeholder="AO号"
        size="large"
        @press-enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" class="input-col">
      <a-input
        v-model="formValues.itemCode"
        placeholder="图号"
        size="large"
        @press-enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" class="input-col">
      <a-input
        v-model="formValues.qualityCode"
        placeholder="质量编号"
        size="large"
        @press-enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" class="input-col">
      <a-input
        v-model="formValues.station"
        placeholder="站位"
        size="large"
        @press-enter="handleSearch"
      />
    </a-col>
    <a-col :span="6" class="input-col">
      <a-select
        v-model="formValues.isSort"
        placeholder="请选择分拣状态"
        @press-enter="handleSearch"
      >
        <a-option value="N">未分拣</a-option>
        <a-option value="Y">已分拣</a-option>
      </a-select>
    </a-col>
    <a-col :span="6" class="input-col">
      <a-select
        v-model="formValues.state"
        placeholder="请选择配套状态"
        @press-enter="handleSearch"
      >
        <a-option value="01">无库存</a-option>
        <a-option value="02">满配</a-option>
      </a-select>
    </a-col>
    <a-col :span="6" class="input-col">
      <a-select
        v-model="formValues.status"
        placeholder="请选择配送状态"
        @press-enter="handleSearch"
      >
        <a-option value="00">已装车未配送</a-option>
        <a-option value="02">已配送</a-option>
        <a-option value="01">未装车</a-option>
      </a-select>
    </a-col>
    <a-col :span="6" class="input-col">
      <a-select
        v-model="formValues.isDailyPlan"
        placeholder="是否下达日计划"
        @press-enter="handleSearch"
      >
        <a-option value="Y">已下达</a-option>
        <a-option value="N">未下达</a-option>
      </a-select>
    </a-col>
  </a-row>
  <div>
    <a-button type="primary" size="large" @click="handleSearch">查询</a-button>
    <a-button class="btn-reset" size="large" @click="reset">重置</a-button>
    <a-button type="outline" size="large" @click="exportExcel">导出</a-button>
  </div>
  <a-divider style="margin-bottom: 8px" />
  <a-radio-group
    v-model:model-value="checkValue"
    style="margin-bottom: 16px"
    default-value="checkInfo"
    @change="handleSearch"
  >
    <a-radio value="checkInfo">查看配套明细</a-radio>
    <a-radio value="checkTool">查看配送托盘</a-radio>
    <a-radio value="checkDetail">查看配送明细</a-radio>
    <a-radio value="checkTotal">查看配送总计</a-radio>
  </a-radio-group>
</template>

<style scoped>
  .input-col {
    margin-bottom: 16px;
  }
  .btn-reset {
    margin-left: 10px;
    margin-right: 10px;
  }
</style>
